package chatroom;

import com.alibaba.fastjson.JSON;
import constutil.Constants;
import constutil.MyMsgUtil;
import constutil.Result;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Gong
 * @Description 收消息
 * @dATE 2022/4/18 16:37
 **/
@WebServlet("/roundMsgServlet")  //不能重名
public class RoundMsgServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        //活的消息数据
        String fromName = (String)req.getSession().getAttribute(Constants.SESSION_USER_ID);//发送者
        String toName = req.getParameter("toName");//接受者

        String mysSessionKey = MyMsgUtil.getMySessionKey(fromName,toName);
        ServletContext sc = this.getServletContext();
        Object chatSession = sc.getAttribute(mysSessionKey);
        Result res = new Result(200,"success");
        res.setOther(chatSession);
        //将JSON对象转化为字符串
        String objStr = JSON.toJSONString(res);
        resp.getWriter().write(objStr);
        resp.getWriter().flush();
        resp.getWriter().close();
    }
}
